

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class zad2 {

	Map<String, Integer> piorMap = new HashMap<String, Integer>();
	Integer maxPior = 0;
	int size;

	long lastTime;

	static Random r = new Random();

	class MyThread extends Thread {
		
		int pior = r.nextInt(9) + 1;
		int q = r.nextInt(5) + 5;

		@Override
		public void run() {
			try {
				enter(pior);

				System.out.println("Watek :" + getName() + " pior: " + pior + " kwant:" + q);
				
				while (pior > 0) {
					doSth(pior, q);
					pior--;
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public synchronized void doSth(int pior, int q) throws InterruptedException {

		while (pior < maxPior) {
			wait();
		}
		synchronized (piorMap) {

			System.out.println("czas synchronizacji: "
					+ (System.nanoTime() - lastTime));

			// koniec synchronizacji ^

			System.out.println("Watek " + Thread.currentThread().getName()
					+ " piorytet: " + pior);

			TimeUnit.MILLISECONDS.sleep(q);

			System.out.println("Spalem przez " + q);

			// poczatek synchronizacji
			lastTime = System.nanoTime();

			piorMap.put(Thread.currentThread().getName(), pior - 1);
			maxPior = Collections.max(piorMap.values());
		}
		notifyAll();

	}
	
	public void simulate(int size){
		
		this.size = size;
		
		for (int i = 0; i < size; i++) {
			new MyThread().start();
		}
		
	}

	public synchronized void enter(int pior) throws InterruptedException {
		synchronized (piorMap) {

			piorMap.put(Thread.currentThread().getName(), pior);
			maxPior = Collections.max(piorMap.values());

		}
	}

	public static void main(String[] args) {
		new zad2().simulate(5);
	}
}

